<?php

namespace App\Service;

use App\Model\MyObject;
use Hyperf\Logger\LoggerFactory;
use Psr\Log\LoggerInterface;

class MyObjectService
{
    protected LoggerInterface $logger;

    public function __construct(LoggerFactory $loggerFactory)
    {
        $this->logger = $loggerFactory->get('my_object');
    }

    public function fetchObjects(int $page)
    {
        return MyObject::query()
            ->orderByDesc('id')
            ->forPage($page)->get()->toArray();
    }

    public function createObject(string $name, string $url, string $address, ?string $brief)
    {
        MyObject::query()->create([
            'name' => $name,
            'url' => $url,
            'brief' => $brief ?? '',
            'address' => $address,
        ]);
    }

    public function updateObject(int $id, string $name, string $url, string $address, string $brief)
    {
        MyObject::query()->where('id', $id)->update([
            'name' => $name,
            'url' => $url,
            'brief' => $brief,
            'address' => $address,
        ]);
    }

    public function searchObjects(string $search)
    {
        return MyObject::query()
            ->orderByDesc('id')
            ->where('name', 'like', '%' .$search. '%')
            ->get()->toArray();
    }

    public function removeObject(int $id)
    {
        MyObject::query()->where('id', $id)->delete();
    }
}